package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public Result serachAll() {
        List<Book> all = bookService.findAll();
        return new Result(Code.GET_OK, all, "你成功了么");
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        Book byId = bookService.findById(id);
        int i = id / 0;
        return new Result(Code.GET_OK, byId, "你成功了么");
    }

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERROR, flag, "null");
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERROR, flag, "null");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERROR, flag, "null");
    }

}
